package com.axialproject.health.exchange.demo;

import com.axialproject.health.exchange.EMF;
import com.axialproject.health.exchange.PatientManager;
import com.axialproject.health.exchange.entity.Patient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author Michael Yuan
 */
public class SendFilter implements Filter {

    private static final Logger log = Logger.getLogger(SendFilter.class.getName());

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        EntityManager em = EMF.get().createEntityManager();
        try {
            List <Patient> patients = PatientManager.getPatientsByAppName(em, "ringful-demo");
            List <String> usernames = new ArrayList <String> ();
            for (Patient patient : patients) {
                usernames.add (patient.getUsername());
            }
            req.setAttribute("users", usernames);
        } finally {
            em.close ();
        }

        chain.doFilter(req, resp);
    }

    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void destroy() {
        this.filterConfig = null;
    }

}

